package com.chalk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.chalk.common.constant.CommonConstants;
import com.chalk.common.constant.SecurityConstants;
import com.chalk.common.constant.TypeConstants;
import com.chalk.common.exception.ServiceException;
import com.chalk.config.security.SecurityPasswordUtil;
import com.chalk.model.SysRole;
import com.chalk.model.SysUser;
import com.chalk.service.SysPermissionService;
import com.chalk.service.SysRoleService;
import com.chalk.service.SysUserService;
import com.chalk.vo.SysPermissionVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @date: 2019-03-04 下午 06:12
 * @author: zhaobo0119@outlook.com
 * @Descriptopn:
 */
@Service
public class SysUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws ServiceException {
        SysUser systemUser = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("user_name", username)
                .eq("is_delete", CommonConstants.IsDeleted.NOTDEL.getValue()));
        if (systemUser == null) {
            throw new ServiceException("用户" + username + "不存在");
        }
        //是否禁用
        if (systemUser.getIsAvailable().equals(TypeConstants.YesOrNo.NO.getValue())) {
            throw new ServiceException("用户" + username + "已禁用");
        }

        //是否锁定
        if (systemUser.getLoginLockStatus().equals(TypeConstants.YesOrNo.YES.getValue())) {
            throw new ServiceException("用户" + username + "已锁定");
        }

        //是否删除
        if (systemUser.getIsDelete().equals(CommonConstants.IsDeleted.DEL.getValue())) {
            throw new ServiceException("用户" + username + "已删除");
        }

        /* 权限业务 */
        Set<String> dbAuthsSet = new HashSet<>();
        /*查询参数*/
        Map<Object, Object> params = new HashMap<>();
        params.clear();
        params.put("userId", systemUser.getUserId());
        /* 查询角色 */
        List<SysRole> platformRoleModels = roleService.selectUserRoleByMap(params);
        if (platformRoleModels != null && platformRoleModels.size() > 0) {
            platformRoleModels.forEach(model -> {
                if (StringUtils.isNoneBlank(model.getMark())) {
                    dbAuthsSet.add(SecurityConstants.ROLE + model.getMark());
                }
            });
        }
        /* 登录角色 */
        dbAuthsSet.add(SecurityConstants.ROLE_LOGIN);
        /* 查询权限 */
        List<SysPermissionVo> menuList = permissionService.selectMenus(params);
        if (menuList != null && menuList.size() > 0) {
            menuList.forEach(menu -> {
                if (StringUtils.isNoneBlank(menu.getPermission())) {
                    dbAuthsSet.add(menu.getPermission());
                }
            });
        }
        Collection<? extends GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        /* 构造security用户 */
        return new User(username, SecurityPasswordUtil.MD5 + systemUser.getPassword(), true,
                true, true, true, grantedAuthorities);
    }


}
